package cn.rongdao.jrkabao.ui.remind;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.mifengkong.frtools.http.request.callback.FRBaseObserver;
import com.mifengkong.frtools.ui.activity.FRStartActivity;
import com.mifengkong.frtools.util.FRDisplayMetrics;
import com.mifengkong.frtools.util.FRString;
import com.mifengkong.frtools.util.FRToast;
import com.mifengkong.kotlincommon.indicator.IndicatorAdapter;
import com.mifengkong.kotlincommon.indicator.TrackIndicatorView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.rongdao.jrkabao.R;
import cn.rongdao.jrkabao.base.BaseAutoFinishActivity;
import cn.rongdao.jrkabao.bean.remind.RemindBean;
import cn.rongdao.jrkabao.bean.remind.RemindExportBillBean;
import cn.rongdao.jrkabao.model.remind.RemindDetailsModel;
import cn.rongdao.jrkabao.model.remind.RemindExportBillModel;
import cn.rongdao.jrkabao.ui.remind.event.DeleteCardEvent;
import cn.rongdao.jrkabao.ui.remind.event.MoXieLooperEvent;
import cn.rongdao.jrkabao.ui.remind.event.RemindChangeStatusSuccessEvent;
import cn.rongdao.jrkabao.ui.remind.event.SaveCardEvent;
import cn.rongdao.jrkabao.ui.remind.fragment.FragmentBill;
import cn.rongdao.jrkabao.ui.remind.fragment.FragmentService;
import cn.rongdao.jrkabao.ui.remind.uicomponent.RemindDetailsTitleBarUIComponent;
import cn.rongdao.jrkabao.ui.remind.uicomponent.RemindDetailsUIComponent;
import cn.rongdao.jrkabao.util.CommonUtil;
import cn.rongdao.jrkabao.util.GetDefaultDataUtil;
import cn.rongdao.jrkabao.util.LoginUtil;
import cn.rongdao.jrkabao.util.moxie.MoXieManager;
import cn.rongdao.jrkabao.widget.SelectPaymentWayFromBottom;

/**
 * Created by jack on 2017/9/13
 */

public class RemindDetailsActivity extends BaseAutoFinishActivity {

    private static final String REMIND_ID = "remind_id";

    public static void start(Context context, String remindId) {
        Bundle bundle = new Bundle();
        bundle.putString(REMIND_ID, remindId);
        FRStartActivity.start(context, RemindDetailsActivity.class, bundle);
    }

    @BindView(R.id.ard_titlebar)
    RemindDetailsTitleBarUIComponent titleBarUIComponent;
    @BindView(R.id.ard_remind_details)
    RemindDetailsUIComponent remindDetailsUIComponent;
    @BindView(R.id.ard_track_indicator_view)
    TrackIndicatorView mTrackIndicatorView;
    @BindView(R.id.ard_view_pager)
    ViewPager mViewPager;

    private List<Fragment> mFragmentList = new ArrayList<>();
    private List<String> mTitleList = new ArrayList<>();

    private String remindId = "";
    private MoXieManager moXieManager;
    private String jumpEmail;
    private boolean isMoXieExportIng = false;
    private String buttonStatus;
    private String isExport;
    private boolean isFirst = true;
    private SelectFromBottomManager selectFromBottomManager;
    private Fragment fragmentBill;

    @Override
    protected int layoutRes() {
        return R.layout.activity_remind_details;
    }

    @Override
    protected void initView() {
        super.initView();
        remindId = getIntent().getStringExtra(REMIND_ID);
        titleBarUIComponent.setRemindId(remindId);
        moXieManager = new MoXieManager(this);
        moXieManager.initKaMaoMoXie();
        selectFromBottomManager = new SelectFromBottomManager(this);
        if (FRString.isEmpty(remindId)) {
            setRemindCardData(GetDefaultDataUtil.getExampleBean());
        }
        initTitleBar();
        initFragmentAndDrawable();
        initTab();
        initData();
        initListener();
    }

    private void setRemindCardData(RemindBean.RemindBankList remindBean) {
        isExport = remindBean.getIs_export();
        remindDetailsUIComponent.seWhiteRemindBean(remindBean);
        titleBarUIComponent.setBankName(remindBean.getBank_name(), remindBean.getBankcard_no());
    }

    private void initFragmentAndDrawable() {
        fragmentBill = new FragmentBill();
        Fragment fragmentService = new FragmentService();

        ((FragmentService) fragmentService).setRemindId(remindId);
        ((FragmentBill) fragmentBill).setRemindId(remindId);

        mFragmentList.add(fragmentBill);
        mTitleList.add("账单");
        mFragmentList.add(fragmentService);
        mTitleList.add("服务");
    }

    private void initTab() {
        mViewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return mFragmentList.get(position);
            }

            @Override
            public int getCount() {
                return mFragmentList.size();
            }
        });

        mTrackIndicatorView.setAdapter(new IndicatorAdapter() {
            @Override
            public int getItemCount() {
                return mFragmentList.size();
            }

            @NonNull
            @Override
            public View getView(int position, @NotNull ViewGroup parent) {
                TextView tvTab = (TextView) LayoutInflater.from(thisActivity()).inflate(R.layout.layout_loan_tab, parent, false);
                tvTab.setText(mTitleList.get(position));
                return tvTab;
            }

            @Override
            public void highLightIndicator(@NotNull View view) {
                view.setSelected(true);
            }

            @Override
            public void resetIndicator(@NotNull View view) {
                view.setSelected(false);
            }

            @Override
            public View getBottomTrackView() {
                View view = new View(thisActivity());
                view.setLayoutParams(new ViewGroup.LayoutParams(FRDisplayMetrics.dp2px(thisActivity(), 100), FRDisplayMetrics.dp2px(thisActivity(), 2)));
                view.setBackgroundColor(ContextCompat.getColor(thisActivity(), R.color.colorPrimary));
                return view;
            }
        }, mViewPager);
    }

    private void initListener() {
        moXieManager.setOnMoXieReturnListener(new MoXieManager.OnMoXieReturnListener() {
            @Override
            public void looperMethod(String email) {
                getMoXieStatusData(email);
            }

            @Override
            public void successReturn(String email) {
                isMoXieExportIng = true;
                ((FragmentBill) fragmentBill).setIsMoXieExport(true);
                titleBarUIComponent.startAnim();
            }
        });

        remindDetailsUIComponent.setRepaymentClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (FRString.isEmpty(remindId)) {
                    FRToast.showToastSafe("不妨添加信用卡试试");
                    return;
                }
                if (buttonStatus.equals("2")) {
                    startMoXieWithEmail();
                    return;
                }
                selectFromBottomManager.showPaymentPop(buttonStatus);
            }
        });

        remindDetailsUIComponent.setWhiteCheckBalanceClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectFromBottomManager.showCheckBalancePop(isExport);
            }
        });

        selectFromBottomManager.setOnCheckBalanceClickListener(new SelectPaymentWayFromBottom.OnCheckBalanceClickListener() {
            @Override
            public void emailCheck() {
                startMoXieWithEmail();
                selectFromBottomManager.dismissCheckBalancePop();
            }

            @Override
            public void msgCheck() {
                selectFromBottomManager.remindAmountQuery(RemindDetailsActivity.this, remindId);
            }
        });

        selectFromBottomManager.setOnSelectListener(new SelectPaymentWayFromBottom.OnSelectListener() {
            @Override
            public void onSelect(boolean isSelected) {
                selectFromBottomManager.remindChangeRepayStatus(RemindDetailsActivity.this, remindId, isSelected);
            }
        });

        selectFromBottomManager.setOnChangeRepayStatusListener(new SelectFromBottomManager.OnChangeRepayStatusListener() {
            @Override
            public void onChangeRepayStatusSuccess() {
                EventBus.getDefault().post(new RemindChangeStatusSuccessEvent());
                selectFromBottomManager.dismissPaymentPop();
                initData();
            }
        });
    }

    public void startMoXieWithEmail() {
        if (isMoXieExportIng) {
            FRToast.showToastSafe("数据获取中，请稍候再试....");
            return;
        }
        moXieManager.startMoXieWithEmail(jumpEmail);
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void deleteCardMessage(DeleteCardEvent deleteCardEvent) {
        finish();
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void saveCardMessage(SaveCardEvent saveCardEvent) {
        initData();
    }

    private void getMoXieStatusData(String email) {
        RemindExportBillModel.getInstance().execute(CommonUtil.isStatusSuccess(isExport), email, new FRBaseObserver<RemindExportBillBean>(this) {
            @Override
            protected void onBaseNext(RemindExportBillBean data) {
                if (CommonUtil.isStatusSuccess(data.getExport_status())) {
                    finishMoXieExport();
                    EventBus.getDefault().post(new MoXieLooperEvent());
                    ((FragmentBill) fragmentBill).initData();
                    initData();
                }
            }

            @Override
            protected void onBaseError(Throwable t) {
                super.onBaseError(t);
                finishMoXieExport();
            }
        });
    }

    private void finishMoXieExport() {
        isMoXieExportIng = false;
        titleBarUIComponent.clearAnim();
        ((FragmentBill) fragmentBill).setIsMoXieExport(false);
        moXieManager.onStop();
    }

    private void initData() {
        if (!FRString.isEmpty(remindId)) {
            RemindDetailsModel.getInstance().execute(remindId, new FRBaseObserver<RemindBean.RemindBankList>(this, isFirst ? "加载中，请稍后..." : "") {
                @Override
                protected void onBaseNext(RemindBean.RemindBankList data) {
                    if (isFirst) {
                        isFirst = false;
                    }
                    if (null != data) {
                        jumpEmail = data.getEmail();
                        buttonStatus = data.getButton_status();
                        setRemindCardData(data);
                    }
                }
            });
        }
    }

    private void initTitleBar() {
        titleBarUIComponent.initLeftBack();
        titleBarUIComponent.setOnRefreshClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!LoginUtil.isLogin(thisActivity())) {
                    return;
                }
                if (FRString.isEmpty(remindId)) {
                    FRToast.showToastSafe("不妨添加信用卡试试");
                    return;
                }
                startMoXieWithEmail();
            }
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
        moXieManager.onStop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        moXieManager.onDestroy();
    }
}